package com.bsj.power.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bsj.power.common.config.global.JsonResult;
import com.bsj.power.common.constant.NumericalConstants;
import com.bsj.power.common.def.dto.PageDTO;
import com.bsj.power.common.def.entity.syncLog.SyncLog;
import com.bsj.power.common.def.vo.sys.SyncLogVO;
import com.bsj.power.common.mapper.SyncLogMapper;
import com.bsj.power.common.util.DateUtils;
import com.bsj.power.system.service.SyncLogService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author LiJiaXin
 * @version 1.0.0
 * @description SyncLogServiceImpl
 * @time 2024/8/27 9:26
 */
@Service
public class SyncLogServiceImpl implements SyncLogService {

    @Resource
    private SyncLogMapper syncLogMapper;

    /**
     * 分页展示同步日志
     *
     * @param pageDTO
     * @return com.bsj.power.common.config.global.JsonResult<java.util.List < com.bsj.power.common.def.vo.sys.SyncLogVO>>
     * @author ljx
     * @time 2024/8/27 9:39
     */
    @Override
    public JsonResult<List<SyncLogVO>> page(PageDTO pageDTO) {
        IPage<SyncLog> page = new Page<>(pageDTO.getPageNumber(), pageDTO.getPageSize());
        QueryWrapper<SyncLog> queryWrapper = new QueryWrapper<>();
        String startTime = pageDTO.getStartTime();
        String endTime = pageDTO.getEndTime();
        if (!StringUtils.isAllBlank(startTime, endTime)) {
            queryWrapper.lambda().between(SyncLog::getCreateTime, startTime, endTime);
        }
        queryWrapper.lambda().orderByDesc(SyncLog::getCreateTime);
        IPage<SyncLog> iPage = syncLogMapper.selectPage(page, queryWrapper);
        long total = iPage.getTotal();
        if (total == NumericalConstants.ZERO) {
            return JsonResult.success(new ArrayList<>(), total);
        }
        List<SyncLogVO> syncLogVOS = iPage.getRecords().stream().map(syncLog -> {
            SyncLogVO syncLogVO = new SyncLogVO();
            BeanUtils.copyProperties(syncLog, syncLogVO);
            syncLogVO.setCreateTime(DateUtils.dateToStr(syncLog.getCreateTime()));
            return syncLogVO;
        }).collect(Collectors.toList());
        return JsonResult.success(syncLogVOS, total);
    }
}
